package com.pv.bfc.web;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.pv.bfc.dao.UserRepository;
import com.pv.bfc.model.BriefcaseUser;

@SuppressWarnings("deprecation")
public class LogInController extends SimpleFormController {

	/**
	 * The view to forward to in case an folder needs to be created.
	 */
	private static final String SUCCESS_VIEW = "usercreated";
	private static final String FAILURE_VIEW = "signon";

	/**
	 * The model key used to retrieve the message from the model.
	 */
	private static final String MODEL_KEY = "message";
	/**
	 * The unique key for retrieving the text associated with this message.
	 */
	private static final String MSG_CODE_VALID = "message.user.validuser";
	private static final String MSG_CODE_UN = "message.user.invalidusername";
	private static final String MSG_CODE_PWD = "message.user.invalidpassword";

	UserRepository userRepo;

	public LogInController() {
		setCommandName("BriefcaseUser");
		setCommandClass(BriefcaseUser.class);
	}

	@Override
	protected ModelAndView onSubmit(Object user, BindException errors)
			throws Exception {
		ModelAndView mav = null;
		BriefcaseUser bfcuser = (BriefcaseUser) user;
		String username = bfcuser.getUserName();
		String password = bfcuser.getPassword();
		BriefcaseUser account = userRepo.retreiveUserByUserName(username);
		if ((username == account.getUserName())
				|| (username.equals(account.getUserName()))) {
			if ((password == account.getPassword())
					|| (password.equals(account.getPassword()))) {
				mav = new ModelAndView(SUCCESS_VIEW, "user", bfcuser);
				mav.addObject(MODEL_KEY, MSG_CODE_VALID);
			} else {
				mav = new ModelAndView(FAILURE_VIEW, "user", bfcuser);
				mav.addObject(MODEL_KEY, MSG_CODE_PWD);
			}

		} else {
			mav = new ModelAndView(FAILURE_VIEW, "user", bfcuser);
			mav.addObject(MODEL_KEY, MSG_CODE_UN);
		}
		return mav;
	}

	public void setUserRepo(UserRepository userRepo) {
		this.userRepo = userRepo;
	}
}
